package com.exchange.used.config.utils;

import com.exchange.used.config.query.Where;
import com.exchange.used.config.query.Condition;

import java.util.Map;

public class SuperSqlBuilder {
    private StringBuilder sb;
    private Condition condition;

    public SuperSqlBuilder(Condition condition){
        if(condition.getFirstTable() == null || condition.getFirstTable().isEmpty()){
            throw new RuntimeException("firstTable can not be null or empty!");
        }

        this.condition = condition;
    }

    public String getSql(){
        sb = new StringBuilder("select * from " + condition.getFirstTable());
        setRelation();
        setCondition();
        setOrder();
        setPage();
        System.out.println("Query SQL : " + sb.toString());
        return sb.toString();
    }

    public String getCount(){
        sb = new StringBuilder("select count(*) count from " + condition.getFirstTable());
        setRelation();
        setCondition();
        System.out.println("Count SQL : " + sb.toString());
        return sb.toString();
    }

    /**
     * 设置连接查询的关联关系
     */
    private void setRelation(){
        if(condition.getRelations() == null){
            return;
        }
        for(Map.Entry<String , String> entry : condition.getRelations().entrySet()){
            sb.append(" left join " + entry.getValue().split("\\.")[0]);
            sb.append(" on " + entry.getKey() + "=" + entry.getValue());
        }
    }


    /**
     * is not null  -2
     * is null      -1
     * !=           0
     * =            1
     * like         2
     */
    private void setCondition(){
        if(condition.getWheres() == null){
            return;
        }
        sb.append(" where 1=1 ");
        for (Where where : condition.getWheres()){
            String value = where.getValue();
            //若条件值为空(包括空格字符)，则不作为检索条件
            if(value != null && !value.trim().isEmpty()){
                sb.append(" and " + where.getField());
                int mode;
                try {
                    mode = Integer.parseInt(where.getMode());
                    if(mode == -2){
                        sb.append(" is not null ");
                    }else if(mode == -1){
                        sb.append(" is null ");
                    }else if(mode == 0){
                        sb.append("!='" + value.trim() + "' ");
                    }else if(mode == 1){
                        sb.append("='" + value.trim() + "' ");
                    }else if(mode == 2){
                        sb.append(" like '%" + value.trim() + "%' ");
                    }else {
                        throw new RuntimeException("检索条件状态值异常");
                    }
                }catch (NumberFormatException e){
                    System.out.println(FastUtils.hightLightLog(e.getMessage()));
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }

    /*
    //用于Oracle数据库
    private void setPageable(){
        if(term.getPageable() == null){
            return;
        }
        sb.insert(0, "select * from( select a.*,rownum r from ( ");
        sb.append(" ) a where ROWNUM<=" +
                term.getPageable().getPageSize() * term.getPageable().getPageNumber() +
                " ) where r>" +
                term.getPageable().getPageSize() * (term.getPageable().getPageNumber() - 1)
        );
    }
    */

    //用于MySQL数据库
    private void setOrder(){
        if(condition.getOrder() == null){
            return;
        }
        sb.append(" order by " + condition.getOrder().getField());
        if(!condition.getOrder().isMode()){
            sb.append(" desc ");
        }
    }

    private void setPage(){
        if(condition.getPage() == null){
            return;
        }
        int left = condition.getLimit() * (condition.getPage() - 1);
        int right = condition.getLimit();
        sb.append(" limit " + left + "," + right);
    }

}
